<script setup lang="ts">
  import { computed, nextTick, ref } from 'vue'
  import Header from './Header.vue'
  import Table from './Table.vue'
  import Pagination from '@/components/Pagination/index.vue'

  defineOptions({
    name: 'GoodSettleSet',
  })

  const tableInstance = ref<InstanceType<typeof Table> | null>(null)
  const headerInstance = ref<InstanceType<typeof Header> | null>(null)
  const paginationInstance = ref<InstanceType<typeof Pagination> | null>(null)
  const getListParam = ref<OrderAPIRequest.GoodSettles>({
    goodsKeyword: '',
    goodsOneTypeId: '',
    goodsTwoTypeId: '',
    goodsThreeTypeId: '',
    name: '',
    limit: 50,
    page: 1,
  })
  const selectedGoodSettleIds = ref<Array<string>>([])
  const getListTotal = computed(() => {
    if (tableInstance.value) {
      return tableInstance.value.total
    }

    return 0
  })

  const handleUpdateList = (param: Omit<OrderAPIRequest.GoodSettles, 'limit' | 'page'>) => {
    Object.assign(getListParam.value, param)
    getList()
  }

  const getList = () => {
    nextTick(() => {
      if (tableInstance.value && paginationInstance.value && headerInstance.value) {
        headerInstance.value.getGoodTypeOptions()
        getListParam.value.limit = paginationInstance.value.size
        getListParam.value.page = paginationInstance.value.current
        tableInstance.value.getList(getListParam.value)
      }
    })
  }

  const handleSelectGoodSettle = (goodSettleIds: Array<string>) => {
    selectedGoodSettleIds.value = goodSettleIds
  }

  defineExpose({
    getList,
  })
</script>

<template>
  <div class="good-settle-set">
    <Header
      ref="headerInstance"
      :settle-ids="selectedGoodSettleIds"
      @update="handleUpdateList"
    ></Header>
    <div class="table">
      <Table ref="tableInstance" @select-good-settle="handleSelectGoodSettle"></Table>
    </div>
    <div class="pagination">
      <pagination
        ref="paginationInstance"
        :list_total="getListTotal"
        @size-change="getList"
        @current-change="getList"
      ></pagination>
    </div>
  </div>
</template>

<style scoped lang="scss">
  .good-settle-set {
    display: flex;
    flex-direction: column;
    row-gap: 5px;
    padding-top: 12px;
    height: 100%;
    box-sizing: border-box;

    .table {
      max-height: calc(100% - 66px);
    }

    .pagination {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
